const axios = require('axios')
const trash = require('@/utils/ini.util')

function apiCreateQRCode ({ accessToken, path }) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url: `https://api.weixin.qq.com/wxa/getwxacode?access_token=${accessToken}`,
      data: {
        path,
        width: 280,
        is_hyaline: true
      },
      responseType: 'arraybuffer'
    }).then(response => {
      if (Object.prototype.toString.call(response.data) === '[object Uint8Array]') {
        resolve(Buffer.from(response.data, 'binary').toString('base64'))
      } else {
        reject(response.data)
      }
    }).catch(error => {
      reject(error)
    })
  })
}

function apiLoginMiniWeb (code) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url: 'https://api.weixin.qq.com/sns/jscode2session',
      params: {
        appid: trash.appid,
        secret: trash.secret,
        js_code: code,
        grant_type: 'authorization_code'
      }
    }).then(response => {
      if (response.status === 200 && !response.data?.errcode) {
        resolve(response.data)
      } else {
        reject(response.data)
      }
    }).catch(error => {
      reject(error)
    })
  })
}

function apiSetApprovelArcReult (articleId, status, reason) {
  return new Promise((resolve, reject) => {
    axios({
      method: 'post',
      url: 'http://127.0.0.1:5555/gimishare/api/v1/articles/get-approvel-result',
      data: {
        articleId,
        status,
        reason
      }
    }).then(response => {
      if (response.status === 200 && response.data?.code === '0') {
        resolve(response.data)
      } else {
        reject(response.data)
      }
    }).catch(error => {
      reject(error)
    })
  })
}

module.exports = {
  apiCreateQRCode,
  apiLoginMiniWeb,
  apiSetApprovelArcReult
}
